<?php
//版权所有(C) 2014 www.ilinei.com

namespace admin\model;

//模板解析器
class _ilinei{
    //获取模板页面，前台缓存
    public function load($theme){
        //加载模板页面缓存
        $pages = cache_read('pages');

        if(empty($pages)){
            $info_xml = (array)simplexml_load_file(ROOTPATH."/tpl/{$theme}/_info.xml");
            $_info_xml_pages = (array)$info_xml['pages'];

            if(is_array($_info_xml_pages['page'])){
                foreach($_info_xml_pages['page'] as $key => $page){
                    $page = (array)$page;

                    //取出当前结点，指定类型为页面
                    $page = $page['@attributes'];
                    $page['type'] = 'page';

                    $pages[$page['file']] = $page;
                }
            }else{
                $page = (array)$_info_xml_pages['page'];

                //取出当前结点，指定类型为页面
                $page = $page['@attributes'];
                $page['type'] = 'page';

                $pages[$page['file']] = $page;
            }

            //写入缓存
            cache_write('pages', $pages);
        }

        return $pages;
    }

    //获取当前模板的页面+块，后台编辑暂不缓存了。
    public function fetch($path){
        global $setting;

        //模板路径指定文件夹为page
        if($path != '/page') return array();

        $themes = explode('/', $setting['SiteTheme']);

        //如果当前模板无描述文件，拜拜吧
        if(!is_file(ROOTPATH."/tpl/{$themes[1]}/_info.xml")) return array();

        $pages = array();
        $info_xml = (array)simplexml_load_file(ROOTPATH."/tpl/{$themes[1]}/_info.xml");
        $_info_xml_pages = (array)$info_xml['pages'];

        if(is_array($_info_xml_pages['page'])){
            foreach($_info_xml_pages['page'] as $key => $page){
                $page = (array)$page;

                //取出当前结点，指定类型为页面
                $page = $page['@attributes'];
                $page['type'] = 'page';

                $pages[$page['file']] = $page;
            }
        }else{
            $page = (array)$_info_xml_pages['page'];

            //取出当前结点，指定类型为页面
            $page = $page['@attributes'];
            $page['type'] = 'page';

            $pages[$page['file']] = $page;
        }

        if(is_array($_info_xml_pages['block'])){
            foreach($_info_xml_pages['block'] as $key => $page){
                $page = (array)$page;

                //取出当前结点，指定类型为块
                $page = $page['@attributes'];
                $page['type'] = 'block';

                $pages[$page['file']] = $page;
            }
        }else{
            $page = (array)$_info_xml_pages['block'];

            //取出当前结点，指定类型为块
            $page = $page['@attributes'];
            $page['type'] = 'block';

            $pages[$page['file']] = $page;
        }

        return $pages;
    }

    //取出页面+块头部描述
    public function desc($file){
        $lines = get_file_lines($file, 2);

        if(substr($lines[0], 0, 10) == '<!--{@page') return substr(str_replace('}-->', '', $lines[0]), 10);
        elseif(substr($lines[0], 0, 11) == '<!--{@block') return substr(str_replace('}-->', '', $lines[0]), 11);

        return '';
    }

    //添加页面
    public function append($pages, $page){
        global $setting;

        $info_xml = (array)simplexml_load_file(ROOTPATH."/{$setting[SiteTheme]}/_info.xml");

        $info_xml_content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<theme>
	<application>{$info_xml[application]}</application>
	<name>{$info_xml[name]}</name>
	<version>{$info_xml[version]}</version>
	<author>{$info_xml[author]}</author>
	<thumb>{$info_xml[thumb]}</thumb>
	<pages>";

        foreach($pages as $key => $item){
            if(empty($item['file'])) continue;

            $info_xml_content .= "
        <{$item[type]} file=\"{$item[file]}\" name=\"{$item[name]}\"/>";
        }

        $info_xml_content .= "
        <{$page[type]} file=\"{$page[file]}\" name=\"{$page[name]}\"/>
    </pages>
</theme>";

        //写入_info.xml文件
        file_put_contents(ROOTPATH."/{$setting[SiteTheme]}/_info.xml", $info_xml_content);

        //删除缓存
        cache_delete('pages');
    }

    //删除页面
    public function delete($pages, $page){
        global $setting;

        $info_xml = (array)simplexml_load_file(ROOTPATH."/{$setting[SiteTheme]}/_info.xml");

        $info_xml_content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<theme>
	<application>{$info_xml[application]}</application>
	<name>{$info_xml[name]}</name>
	<version>{$info_xml[version]}</version>
	<author>{$info_xml[author]}</author>
	<thumb>{$info_xml[thumb]}</thumb>
	<pages>";

        foreach($pages as $key => $item){
            if(empty($item['file']) || $item['file'] == $page) continue;

            $info_xml_content .= "
        <{$item[type]} file=\"{$item[file]}\" name=\"{$item[name]}\"/>";
        }

        $info_xml_content .= "
    </pages>
</theme>";

        //写入_info.xml文件
        file_put_contents(ROOTPATH."/{$setting[SiteTheme]}/_info.xml", $info_xml_content);

        //删除缓存
        cache_delete('pages');
    }

    //TAG模板
    public function block_tpls(){
        $tpls['cms_model_category_multi'] = '
<!--{loop ${VAR} $loop $category}-->
<span class="item">
    <a href="{LINK}.html?no={$category[IDENTITY]}">{$category[CNAME]}</a>
</span>
<!--{/loop}-->';

        $tpls['cms_model_category_crumbs'] = '
<!--{loop ${VAR} $loop $crumb}-->
/ <a href="{LINK}.html?no={$crumb[IDENTITY]}">{$crumb[CNAME]}</a>
<!--{/loop}-->';

        $tpls['cms_model_category_one'] = '<a href="{LINK}.html?no={${VAR}[IDENTITY]}">{${VAR}[CNAME]}</a>';
        $tpls['cms_model_article_multi'] = '
<table>
    <tbody>
    <!--{loop ${VAR} $key $article}-->
    <tr class="row-text">
        <td class="title"><a href="{LINK}.html?id={$article[ARTICLEID]}&page={$_var[page]}" target="_blank">{$article[TITLE]}</a></td>
        <td class="pubdate">{echo date("m-d H:i", strtotime($article["PUBDATE"]));}</td>
        <td class="hits">{$article[HITS]}</td>
        <td class="down">{$article[DOWN]}</td>
    </tr>
    <tr class="row-image">
        <td class="left">
            <a href="{LINK}.html?id={$article[ARTICLEID]}&page={$_var[page]}" title="{$article[TITLE]}" target="_blank">
                <img src="{$article[FILE01][0]}" border="0" alt="{$article[TITLE]}"/>
            </a>
        </td>
        <td>
            <p class="title">
                <a href="{LINK}.html?id={$article[ARTICLEID]}&page={$_var[page]}">{$article[TITLE]}</a>
            </p>
            <p class="subtitle">{$article[SUBTITLE]}</p>
            <p class="writer">作者：{$article[KEYWORDS]}</p>
            <p class="address">来源：{$article[KEYWORDS]}</p>
            <p class="summary">{echo custr($article[\'SUMMARY\'], 120);}</p>
        </td>
        <td class="right">
            <p class="pubdate">{echo date("m-d H:i", strtotime($article["PUBDATE"]));}</p>
            <p class="hits">{$article[HITS]}点击</p>
            <p class="down">{$article[DOWN]}下载</p>
        </td>
    </tr>
    <!--{/loop}-->
    </tbody>
</table>

<!--{if count($articles) == 0}-->
<p class="empty">无记录！</p>
<!--{/if}-->

{$pager}
</table>';

        $tpls['cms_model_article_one'] = '
<table>
    <tbody>
    <tr>
        <td>
            <p class="title">{${VAR}[TITLE]}</p>
            <p class="subtitle">{${VAR}[SUBTITLE]}</p>
        </td>
    </tr>
    <tr class="pub-hit-down">
        <td>
            <span class="pubdate">发布时间：{${VAR}[PUBDATE]}</span>
            <span class="hits">点击：{${VAR}[HITS]}</span>
            <span class="down">下载：{${VAR}[DOWN]}</span>
        </td>
    </tr>
    <tr class="wri-add">
        <td>
            <span class="writer">作者：{${VAR}[WRITER]}</span>
            <span class="address">来源：{${VAR}[ADDRESS]}</span>
        </td>
    </tr>
    <tr class="keywords">
        <td>
            <span class="label">关键词：</span>
            <!--{loop $article[KEYWORDS] $loop $word}-->
            <span class="word">{$word}</span>
            <!--{/loop}-->
        </td>
    </tr>
    <tr class="summary">
        <td>
            <span>摘要：</span>
            <p class="text">{$article[SUMMARY]}</p>
        </td>
    </tr>
    <tr>
        <td>
            <div class="content">{${VAR}[CONTENT]}</div>
        </td>
    </tr>
    <tr class="baidu-share">
        <td>
            <div class="share">
                <div class="icon">
                    <div class="bshare-custom icon-medium">
                        <div class="bsPromo bsPromo2"></div>
                        <a title="分享到" id="bshare-shareto" class="bshare-more">分享到</a>
                        <a title="分享到新浪微博" class="bshare-sinaminiblog"></a>
                        <a title="分享到微信" class="bshare-weixin" href="javascript:void(0);"></a>
                        <a title="分享到QQ好友" class="bshare-qqim" href="javascript:void(0);"></a>
                        <a title="分享到腾讯微博" class="bshare-qqmb"></a>
                        <a title="更多平台" class="bshare-more bshare-more-icon more-style-addthis"></a>
                    </div>
                </div>
            </div>
        </td>
    </tr>
    <tr class="prev-next">
        <td>
            <!--{if $article[\'PREV\']}-->
            <p class="prev">
                <span>< 上一篇：</span>
                <span>
                    <a href="{LINK}.html?id={$article[\'PREV\'][ARTICLEID]}&page={$_var[page]}" title="{$article[PREV][TITLE]}">{$article[PREV][TITLE]}</a>
                </span>
            </p>
            <!--{/if}-->
            <!--{if $article[\'NEXT\']}-->
            <p class="next">
                <span>< 下一篇：</span>
                <span>
                    <a href="{LINK}.html?id={$article[\'NEXT\'][ARTICLEID]}&page={$_var[page]}" title="{$article[NEXT][TITLE]}">{$article[NEXT][TITLE]}</a>
                </span>
            </p>
            <!--{/if}-->
        </td>
    </tr>
    </tbody>
</table>';

        return $tpls;
    }

    //获取单个TAG
    public static function block_tag($tag){
        //TAG内头部添加空TAG
        if($tag[1]){
            $code1 = stripcslashes($tag[1]);
            $code1 = str_replace('BLOCK', '', $code1);
            $code1 = "<!--{TAG_BLOCK{$code1}}-->";
        }

        //当前TAG
        if($tag[0]){
            $code0 = stripcslashes($tag[0]);
            $code0 = str_replace('BLOCK', '', $code0);
            $code0 = "<!--{TAG_BLOCK{$code0}}-->";
        }

        //TAG内底部添加空TAG
        if($tag[2]){
            $code2 = stripcslashes($tag[2]);
            $code2 = str_replace('BLOCK', '', $code2);
            $code2 = "<!--{TAG_BLOCK{$code2}}-->";
        }

        if(!empty($code1) || !empty($code2)) return $code1.$code0.$code2."<!--{/TAG_BLOCK}-->";
        else return $code1.$code0.$code2;
    }

    //块TAG
    public static function block_tags($var){
        global $_var;

        $GLOBALS['_ILINEI_ID'] = $GLOBALS['_ILINEI_ID'] + 1;

        if($var == 'file="meta"') return "<!--{TAG_BLOCK file=\"meta\"}-->";

        $code_prev = $code0 = $code1 = $code2 = $code_next =  "";

        $code_prev =  "";
        foreach($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}_prev"] as $key => $prevs){
            foreach($prevs as $ckey => $prev){
                if(empty($prev)) continue;

                $temp = str_replace('BLOCK', '', stripcslashes($prev));
                $code_prev .= "<!--{TAG_BLOCK{$temp}}-->";
                unset($temp);
            }
        }

        $code_next = "";
        foreach($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}_next"] as $key => $prevs){
            foreach($prevs as $ckey => $prev){
                if(empty($prev)) continue;

                $temp = str_replace('BLOCK', '', stripcslashes($prev));
                $code_next .= "<!--{TAG_BLOCK{$temp}}-->";
                unset($temp);
            }
        }

        //如果当前TAG的参数change为true，代码块发生变更，要重新刷新代码
        //当前TAG
        if($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][0]){
            $code0 = stripcslashes($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][0]);
            $code0 = str_replace('BLOCK', '', $code0);
            $code0 = "<!--{TAG_BLOCK{$code0}}-->";
        }

        //TAG内头部添加空TAG
        if($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][1]){
            $code1 = stripcslashes($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][1]);
            $code1 = str_replace('BLOCK', '', $code1);
            $code1 = "<!--{TAG_BLOCK{$code1}}-->";
        }

        //TAG内底部添加空TAG
        if($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][2]){
            $code2 = stripcslashes($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][2]);
            $code2 = str_replace('BLOCK', '', $code2);
            $code2 = "<!--{TAG_BLOCK{$code2}}-->";
        }

        if(strexists($code0, 'file=')) return $code_prev.$code0.$code1.$code2.$code_next;

        return $code_prev.$code0.$code1.$code2."<!--{/TAG_BLOCK}-->".$code_next;
    }

    //广告位TAG
    public static function adlog_tags($var){
        global $_var;

        $GLOBALS['_ILINEI_ID'] = $GLOBALS['_ILINEI_ID'] + 1;

        $code_prev = $code = $code_next =  "";

        $code_prev =  "";
        foreach($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}_prev"] as $key => $prevs){
            foreach($prevs as $ckey => $prev){
                if(empty($prev)) continue;

                $temp = str_replace('BLOCK', '', stripcslashes($prev));
                $code_prev .= "<!--{TAG_BLOCK{$temp}}-->";
                unset($temp);
            }
        }

        $code_next = "";
        foreach($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}_next"] as $key => $prevs){
            foreach($prevs as $ckey => $prev){
                if(empty($prev)) continue;

                $temp = str_replace('BLOCK', '', stripcslashes($prev));
                $code_next .= "<!--{TAG_BLOCK{$temp}}-->";
                unset($temp);
            }
        }

        //当前TAG
        if($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][0]){
            $code = stripcslashes($_var["gp__ilinei_id_{$GLOBALS[_ILINEI_ID]}"][0]);
            $code = str_replace('ADLOG', '', $code);
            $code = "<!--{TAG_ADLOG{$code}}-->";
        }

        return $code_prev.$code.$code_next;
    }

    //保存解析
    public function save($file){
        global $_var;

        if(!@$fp = fopen($file, 'r')) return '';
        $template = @fread($fp, filesize($file));
        fclose($fp);

        $content = $template;
        $content = preg_replace("/([\n\r]+)\t+/s", "\\1", $content);
        $content = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $content);

        $template = preg_replace("/\<\!\-\-\{adlog(.+?)\}\-\-\>/s", "{adlog\\1}", $template);
        $template = preg_replace("/\<\!\-\-\{block(.+?)\}\-\-\>/s", "{block\\1}", $template);
        $template = preg_replace_callback("/\{adlog\s+(.+?)\}/i", create_function('$matches', 'return \admin\_ilinei::adlog_tags($matches[1]);'), $template);
        $template = preg_replace_callback("/\{block\s+(.+?)\}/is", create_function('$matches', 'return \admin\_ilinei::block_tags($matches[1]);'), $template);

        $body_prev =  "";
        foreach($_var["gp_body_prev"] as $key => $prevs){
            foreach($prevs as $ckey => $prev){
                if(empty($prev)) continue;

                $temp = str_replace('BLOCK', '', stripcslashes($prev));
                $body_prev .= "<!--{TAG_BLOCK{$temp}}-->";
                unset($temp);
            }
        }

        $body_next = "";
        foreach($_var["gp_body_next"] as $key => $prevs){
            foreach($prevs as $ckey => $prev){
                if(empty($prev)) continue;

                $temp = str_replace('BLOCK', '', stripcslashes($prev));
                $body_next .= "<!--{TAG_BLOCK{$temp}}-->";
                unset($temp);
            }
        }

        //这个是页面，还有一个是块头
        if(strpos($template, '<body>') === false){
            $lines = explode("\r\n", $template);

            if(strexists($lines[0], '@block')) $template = $lines[0]."\r\n".$body_prev.implode("\r\n", array_slice($lines, 1));
            else $template = $body_prev.$template;
        }else $template = str_replace('<body>', "<body>{$body_prev}", $template);

        if(strpos($template, '</body>') === false) $template = $template.$body_prev;
        else $template = str_replace('</body>', "{$body_prev}</body>", $template);

        $template = str_replace('TAG_ADLOG', 'adlog', $template);
        $template = str_replace('TAG_BLOCK', 'block', $template);

        return $template;
    }

    //解析块
    public function parse($file, $params){
        $content = $template = '';

        foreach($params as $key => $param){
            $content .= " {$key}=\"{$param}\"";
        }

        $id = str_replace('_ilinei_id_', '', $params['id']) + 0;

        if($id > 0){
            if(!@$fp = fopen($file, 'r')) return '';
            $template = @fread($fp, filesize($file));
            fclose($fp);

            $tpls = $this->block_tpls();

            $blocks = explode('{block', $template);
            $blocks = explode('{/block', $blocks[$id]);

            $template = str_replace('<!--', '', $blocks[0]);
            $template = str_replace('-->', '', $template);

            if(strpos($template, '}') === false || $params['change']){
                //空TAG
                if($params['model'] == '\cms\model\_category' && $params['method'] == 'multi') $template = $tpls['cms_model_category_multi'];
                elseif($params['model'] == '\cms\model\_category' && $params['method'] == 'crumbs') $template = $tpls['cms_model_category_crumbs'];
                elseif($params['model'] == '\cms\model\_category' && $params['method'] == 'one') $template = $tpls['cms_model_category_one'];
                elseif($params['model'] == '\cms\model\_article' && $params['method'] == 'multi') $template = $tpls['cms_model_article_multi'];
                elseif($params['model'] == '\cms\model\_article' && $params['method'] == 'one') $template = $tpls['cms_model_article_one'];

                $template = str_replace('VAR', $params['var'], $template);
            }else{
                $template = "{block".$template;
                $template = substring($template, strpos($template, '}') + 1);
            }
        }

        return "{block{$content}}\r\n{$template}\r\n{/block}";
    }
}
?>